package com.medusa.aps.business.config;

import com.medusa.aps.business.common.model.resp.Result;
import com.medusa.aps.business.common.model.resp.SystemCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author 张治保
 * @since 2024/1/17
 */
@Slf4j
@RestControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class ExceptionAdviceConfig {

    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Result<Object> handleError(HttpMessageNotReadableException e) {
        log.debug("param read error", e);
        Result<Object> failed = Result.failed(SystemCode.MSG_NOT_READABLE);
        if (e.getMessage().contains("integer overflow")) {
            failed.setMsg("页面存在字段输入字符过长，请检查后重新输入");
        }
        return failed;
    }


    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<Object> handleError(MethodArgumentNotValidException e) {
        log.debug("param valid error", e);
        return handleError(e.getBindingResult());
    }

    /**
     * 处理 BindingResult
     *
     * @param result BindingResult
     * @return Result
     */
    protected Result<Object> handleError(BindingResult result) {
        FieldError error = result.getFieldError();
        if (error == null) {
            return Result.failed(SystemCode.PARAM_BIND_ERROR);
        }
        return Result.failed(SystemCode.PARAM_BIND_ERROR, error.getDefaultMessage());
    }
}
